<?php
error_reporting(0);

define('BASEPATH', realpath(dirname(__FILE__)).'/../../../');

if (empty($_FILES)) {
    json_back('XT002', '请选图片');
}

$photo_file = $_FILES['photo_upload'];

//判断上传文件错误
$upload_errors = array(
    UPLOAD_ERR_OK => 'success',
    UPLOAD_ERR_INI_SIZE => '图片大小超过限制',
    UPLOAD_ERR_FORM_SIZE => '图片大小超过表单限制',
    UPLOAD_ERR_PARTIAL => '由于网络问题，图片没能全部上传',
    UPLOAD_ERR_NO_FILE => '上传图片为空',
    UPLOAD_ERR_NO_TMP_DIR => '服务器端错误，没有临时目录',
    UPLOAD_ERR_CANT_WRITE => '图片目录不可写',
    UPLOAD_ERR_EXTENSION => 'php extension stop upload'
);

if ($photo_file['error'] > 0) {
    json_back('XT002', $upload_errors[$photo_file['error']]);
}
/*
 * 判断上传文件类型
 * 判断不出来 换判断文件名后缀
  $allowTypes = array('image/x-png', 'image/png', 'image/pjpeg', 'image/jpeg', 'image/bmp', 'image/gif','application/octet-stream');

  if (!in_array($photo_file['type'], $allowTypes)) {
  json_back('XT002', $photo_file['type'].'file type error');
  }
 */

$name_ext = array_pop(explode('.', $photo_file['name']));

$allow_exts = "jpg|jpeg|gif|bmp|png";

if(!preg_match("/^(:?jpg|jpeg|gif|bmp|png)$/i",$name_ext)){
    json_back('XT002', 'Image type error - ' . $name_ext);
}

unset($allow_exts);

$file = generate_rand_name($photo_file['name']);

$date_string = date('Ymd', time());

$photo_name = $date_string . '/' . $file;

$target_path = str_replace('//', '/', $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/' . $date_string . '/');

if (!file_exists($target_path)) {
    mkdir($target_path, 0777);
}

$target_file = $target_path . $file;

move_uploaded_file($photo_file['tmp_name'], $target_file) or json_back('XT002', 'move file error' . $target_path);

unset($upload_errors, $file, $date_string, $target_path);

$thumb_width = intval($_REQUEST['thumb_width']);
$thumb_height = intval($_REQUEST['thumb_height']);
if($thumb_width == 0 && $thumb_height == 0){
    $thumb_width = $thumb_height = 150;
}

create_thumbnail($target_file, $thumb_width, $thumb_height);

unset($photo_file, $name_ext, $target_file);

//取数据配置
$db_config = load_config('database');
//链接数据库
$mysqli = new mysqli($db_config['hostname'], $db_config['username'], $db_config['password'], $db_config['database']);
unset($db_config);
if (($error = mysqli_connect_error())) {
    json_back('XT002', 'connect failed ');
}

$user = intval($_REQUEST['user']);
$album_name = trim($_REQUEST['albumName']);
$album_description = trim($_REQUEST['albumDescripton']);

//如果是首次上传图片 创建相册
if (!($album = intval($_REQUEST['album']))) {
    $sql = "INSERT INTO `jg_album` VALUES (NULL, '0', '0', '{$album_name}', '{$album_description}', '{$user}', NOW());";
    if ($mysqli->query($sql) !== true) {
        json_back('XT002', 'query album sql error');
    }
    $album = $mysqli->insert_id;
}

$sql = "INSERT INTO `jg_photo` VALUES (NULL, {$album}, '{$photo_name}','temp','description',{$user},NOW());";
if ($mysqli->query($sql) !== true) {
    json_back('XT002', 'query photo sql error');
}
$photo_id = $mysqli->insert_id;

//检查相册有没有设置封面，没有则设置当前图片给封面
$sql = "SELECT `cover` FROM `jg_album` WHERE `id`={$album};";
if (!($result = $mysqli->query($sql))) {
    json_back('XT002', 'get album.cover unsuccess');
}
$album_object = $result->fetch_object();
$result->close();
if ($album_object && $album_object->cover == 0) {
    $sql = "UPDATE `jg_album` SET `cover`={$photo_id} WHERE `id`={$album};";
    if ($mysqli->query($sql) !== true) {
        json_back('XT002', 'set cover error');
    }
}
json_back('XT001', 'SUCCESS', array('album' => $album));

$mysqli->close();

unset($sql, $album, $user, $photo_name, $mysqli, $result);

function generate_rand_name($file_name) {
    $name_segments = explode('.', $file_name);

    $subfix = '.' . array_pop($name_segments);

    return md5(date('YmdHis') . rand(1000, 9999)) . $subfix;
}

function thumb_name($file_name) {
    return preg_replace("/\.([^\.]*)$/", '_thumb.$1', $file_name);
}

function json_back($status, $msg, $data) {
    header('Content-type: application/json; charset=utf-8');

    echo json_encode(array(
        'status' => $status,
        'msg' => $msg,
        'data' => $data
    ));

    exit(0);
}

function load_config($config) {
    $path = realpath(BASEPATH . '/application/config/') . DIRECTORY_SEPARATOR . $config . '.php';

    if (file_exists($path)) {
        include $path;
        return $db['default'];
    }

    die($config . ' not exists.');
}

// IMAGE FUNCTIONS
function image_source($ext, $name) {
    switch ($ext) {
        case 'png':
            return imagecreatefrompng($name);
            break;
        case 'jpeg':
        case 'jpg':
            return imagecreatefromjpeg($name);
            break;
        case 'bmp':
            return imagecreatefromwbmp($name);
            break;
        case 'gif':
            return imagecreatefromgif($name);
            break;
        default:
            exit('image ext type error');
    }
}

function save_image($ext, $source, $name) {
    switch ($ext) {
        case 'png':
            return imagepng($source, $name);
            break;
        case 'jpeg':
        case 'jpg':
            return imagejpeg($source, $name);
            break;
        case 'bmp':
            return imagewbmp($source, $name);
            break;
        case 'gif':
            return imagegif($source, $name);
            break;
    }
}

function calculate_thumb_size($thumb_width, $thumb_height, $image_width, $image_height) {
    //当图片的宽度大于宽度限制 或 高度大于高度限制时 才做压缩
    if ($thumb_height == 0) {
        if ($image_width > $thumb_width) {
            $thumb_height = $image_height / $image_width * $thumb_width;
        } else {
            return false;
        }
    } else if ($thumb_width == 0) {
        if ($image_height > $thumb_height) {
            $thumb_width = $image_width / $image_height * $thumb_height;
        } else {
            return false;
        }
    } else {
        if ($image_width / $image_width > $thumb_width / $thumb_height) {
            if ($image_width > $thumb_width) {
                $thumb_height = $image_height / $image_width * $thumb_width;
            } else {
                return false;
            }
        } else {
            if ($image_height > $thumb_height) {
                $thumb_width = $image_width / $image_height * $thumb_height;
            } else {
                return false;
            }
        }
    }

    return array('width' => $thumb_width, 'height' => $thumb_height);
}

function create_thumbnail($file, $width, $height) {
    if (extension_loaded('gd')) {
        
        $ext = array_pop(explode('.', $file));
        
        $image = image_source($ext, $file);

        $image_width = imagesx($image);
        $image_height = imagesy($image);
        
        $thumb_size = calculate_thumb_size($width, $height, $image_width, $image_height);

        if ($thumb_size !== false) {
            $height = $thumb_size['height'];

            $width = $thumb_size['width'];

            $thumb = imagecreatetruecolor($width, $height);

            imagecopyresized($thumb, $image, 0, 0, 0, 0, $width, $height, $image_width, $image_height);

            save_image($ext, $thumb, thumb_name($file));

            imagedestroy($thumb);
        }

        imagedestroy($image);
        //unset($image_width, $image_height, $width, $height, $ext, $file);
    }
}